<template>
  <a-modal :width="1000" v-model:visible="showChooseProductDialog" :footer="multiple" :title="title" title-align="start" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    <div class="table-model-wrap">
      <a-table size="mini" ref="tableRef" :loading="tableLoading" :data="productList" row-key="id" :scroll="{ y: 'calc(84vh - 230px)' }" @selection-change="selectColumn" :row-selection="multiple ? rowSelection : {}" :bordered="false" class="table-two-line table-model" :pagination="false">
        <template #columns>
          <a-table-column title="序号" :width="45">
            <template #cell="{ rowIndex }">
              <p>{{ rowIndex + 1 }}</p>
            </template>
          </a-table-column>
          <a-table-column title="图片" :width="60">
            <template #cell="{ record }">
              <ImgPopover :src="getPicUrl(record)">
                <template #con>
                  <a-image width="40" height="40" fit="contain" :src="getPicUrl(record)" />
                </template>
              </ImgPopover>
            </template>
          </a-table-column>
          <a-table-column title="SKU" :width="130" dataIndex="sku" />
          <a-table-column title="产品名称" :width="300">
            <template #cell="{ record }">
              <a-popover position="tl" style="width: 400px">
                <p class="text-limit-two">{{ record.skuName }}</p>
                <template #content>
                  <p>{{ record.skuName }}</p>
                </template>
              </a-popover>
            </template>
          </a-table-column>
          <a-table-column :width="100" title="类目">
            <template #cell="{ record }">
              <p>{{ $extract(record, 'category.name') }}</p>
            </template>
          </a-table-column>
          <a-table-column :width="100" title="产品开发员">
            <template #cell="{ record }">
              <p>{{ $extract(record, 'developer.name') }}</p>
            </template>
          </a-table-column>
          <a-table-column :width="100" title="操作" v-if="!multiple">
            <template #cell="{ record }">
              <a-button type="text" size="mini" @click="chooseProduct(record)">选择</a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
    <div class="pagination-footer">
      <a-pagination v-if="needCount" size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      <a-space v-else>
        <a-button v-if="searchVal.pageNum > 1" class="gray-outline" size="small" @click="lastPage">上一页</a-button>
        <a-button v-if="productList.length == searchVal.pageSize" class="gray-outline" size="small" @click="nextPage">下一页</a-button>
      </a-space>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue'
  import ImgPopover from '@/components/imgPopover.vue'
  import { skuPageRelatedForCompanyVer, getCategoryList } from '@/api/product'
  import { Message } from '@arco-design/web-vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { cloneDeep } from 'lodash-es'

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    needCount: {
      type: Boolean,
      default: true,
    },
  })
  onMounted(async () => {
    getCategory()
    getProductList()
  })
  const filterItem: any = reactive([
    {
      type: 'input_keyword',
      key: 'skuList',
      keyItems: [
        { label: 'SKU', value: 'skuList' },
        { label: 'SPU', value: 'spuList' },
        { label: '产品名称', value: 'skuNameList' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: 'SKU',
      width: 200,
      isMultiple: true,
    },
    {
      type: 'cascader',
      key: 'categoryIdList',
      optionItems: [],
      keyWidth: '140',
      value: ref(),
      placeholder: '商品分类',
      label: '类目',
      width: 200,
      isMultiple: true,
    },
  ])

  const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const showChooseProductDialog = ref(props.isShow)
  const searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    searchType: 'exact',
    keywordType: 'skuOrSkuName',
  })
  const total = ref(0)
  const submitLoading = ref(false)
  const selectRow = ref([])
  const productListMap = ref({})
  const productList = ref([])
  const tableRef = ref()
  const tableLoading = ref(false)
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getProductList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getProductList()
  }
  function selectColumn(val: any) {
    selectRow.value = val
  }
  //产品列表数据
  async function getProductList() {
    tableLoading.value = true
    let newValue: any = cloneDeep(searchVal.value)
    newValue.categoryIdList = newValue.categoryIdList ? newValue.categoryIdList.split(',') : []
    newValue.skuList = newValue.skuList ? newValue.skuList.split(',') : []
    newValue.spuList = newValue.spuList ? newValue.spuList.split(',') : []
    newValue.skuNameList = newValue.skuNameList ? newValue.skuNameList.split(',') : []
    newValue.needCount = props.needCount
    const res: any = await skuPageRelatedForCompanyVer(newValue)
    tableLoading.value = false
    productList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
    productListMap.value = {}
    productList.value.forEach((el: any) => {
      productListMap.value[el.id] = el
    })
    tableRef.value.selectAll(false)
  }
  const getCategory = async () => {
    const res: any = await getCategoryList()
    filterItem[1].optionItems = res.data
  }
  const searchByVal = (val: any) => {
    searchVal.value = {}
    searchVal.value = val
    searchVal.value.pageNum = 1
    getProductList()
  }
  const nextPage = () => {
    searchVal.value.pageNum++
    getProductList()
  }
  const lastPage = () => {
    searchVal.value.pageNum--
    getProductList()
  }
  // 显示图片
  function getPicUrl(item: any) {
    return item?.productPicList?.[0]?.url
  }
  // 选择产品
  function chooseProduct(item: any) {
    emit('success', item)
    emit('closed')
  }
  // 关闭
  function closedDialog() {
    showChooseProductDialog.value = false
    emit('closed')
  }
  // 选择产品
  function submitData() {
    if (!selectRow.value.length) {
      Message.error('请选择产品')
      return false
    }
    let list = selectRow.value.map((id: string) => productListMap.value[id])
    emit('success', list)
    emit('closed')
  }
</script>
<style lang="less" scoped>
  .info-text {
    color: #999;
    margin-top: 10px;
  }
  .pagination-footer {
    margin: 10px 0 0;
  }
</style>
